# coding: utf-8
'''
Created on 2015年12月9日

@author: Administrator
'''

import urllib
from django.contrib.auth.models import User

from common.utils import  storage
from message.utils import message_tool
from account import settings
from account.models import Profile
from account.signals import userinfo_update_signal


def __parse_user_attrs(attrs, user_fields, profile_fields):
    
    for attr_name in attrs:
        if attr_name in ['username', 'email']:
            user_fields.append(attr_name)
        elif attr_name == 'nick_name':
            user_fields.append('first_name')
        elif attr_name == 'real_name':
            user_fields.append('last_name')
        elif attr_name in ['utype', 'mobile', 'mobile_authed', 'email_authed', 'sex', 'avatar_fpath', 'origin_avatar_fpath']:
            profile_fields.append(attr_name)
        elif attr_name == 'city_id':
            profile_fields.append('city')
        elif attr_name == 'avatar_url':
            profile_fields.append('avatar_fpath')
    

def fetch_userinfo(user_id, attrs=[]):
    u'''
    function: 根据attrs查询字段查询用户信息
    
    user_id - 用户id
    
    # User attrs
    username - 用户名
    email - Email
    nick_name - 昵称
    real_name - 真实姓名
    
    # Profile attrs
    utype - 用户类型
    mobile - 手机号
    mobile_authed - 是否手机认证
    email_authed - 是否邮箱认证
    avatar_fpath - 头像文件路径
    origin_avatar_fpath - 原始头像文件路径
    avatar_url - 头像url
    city_id - 城市id
    sex - 性别
    
    # 福币
    fcoin_amount - 福币数量
    
    # 未读消息
    message - 未读消息数量，格式: {'total': 10, 'system': 5, 'normal': 2, 'letter': 3}
    
    return: {'user_id': $attr1: 'xxx', $attr2: 'yyy'}
    
    '''
    
    attrs = list(set(attrs))
    
    user_fields = []
    profile_fields = []
    
    data = {
        'user_id': user_id,
    }
    
    __parse_user_attrs(attrs, user_fields, profile_fields)
    
    user_fields = list(set(user_fields))
    profile_fields = list(set(profile_fields))
    
    if user_fields:
        try:
            user = User.objects.only(*user_fields).get(id=user_id)
        except User.DoesNotExist:
            return None
        if 'username' in attrs:
            data['username'] = user.username
        if 'email' in attrs:
            data['email'] = user.email
        if 'nick_name' in attrs:
            data['nick_name'] = user.first_name
        if 'real_name' in attrs:
            data['real_name'] = user.last_name
    
    if profile_fields:
        profile = Profile.objects.only(*profile_fields).get(user=user_id)
        if 'utype' in attrs:
            data['utype'] = profile.utype
        if 'mobile' in attrs:
            data['mobile'] = profile.mobile
        if 'mobile_authed' in attrs:
            data['mobile_authed'] = int(profile.mobile_authed)
        if 'email_authed' in attrs:
            data['email_authed'] = int(profile.email_authed)
        if 'sex' in attrs:
            data['sex'] = profile.sex
        if 'avatar_fpath' in attrs:
            data['avatar_fpath'] = profile.avatar_fpath
        if 'origin_avatar_fpath' in attrs:
            data['origin_avatar_fpath'] = profile.origin_avatar_fpath
        if 'city_id' in attrs:
            data['city_id'] = profile.city_id if profile.city_id else 0
        if 'avatar_url' in attrs:
            data['avatar_url'] = storage.get_absolute_url(profile.avatar_fpath)
    
    if 'message' in attrs:
        data['message'] = message_tool.fetch_user_unreaded_message(user_id)
    
    return data


def fetch_many_userinfo(user_ids, attrs=[]):
    u'''
    function: 根据attrs查询字段查询用户信息
    
    user_ids - 多用户id数组
    
    # User attrs
    username - 用户名
    email - Email
    nick_name - 昵称
    real_name - 真实姓名
    
    # Profile attrs
    mobile - 手机号
    mobile_authed - 是否手机认证
    email_authed - 是否邮箱认证
    avatar_fpath - 头像文件路径
    origin_avatar_fpath - 原始头像文件路径
    avatar_url - 头像url
    city_id - 城市id
    sex - 性别

    return: {'xxxid': {'user_id': $attr1: 'xxx', $attr2: 'yyy'}...}
    '''
    
    attrs = list(set(attrs))
    
    user_fields = []
    profile_fields = []
    
    data = {}
    
    __parse_user_attrs(attrs, user_fields, profile_fields)
    
    user_fields = list(set(user_fields))
    profile_fields = list(set(profile_fields))
    
    if user_fields:
        users = User.objects.only(*user_fields).filter(id__in=user_ids)
        for user in users:
            d = {'user_id': user.id}
            if 'username' in attrs:
                d['username'] = user.username
            if 'email' in attrs:
                d['email'] = user.email
            if 'nick_name' in attrs:
                d['nick_name'] = user.first_name
            if 'real_name' in attrs:
                d['real_name'] = user.last_name
            data[user.id] = d
            
    if profile_fields:
        profiles = Profile.objects.only(*profile_fields).filter(user_id__in=user_ids)
        for profile in profiles:
            d = {}
            if 'utype' in attrs:
                d['utype'] = profile.utype
            if 'mobile' in attrs:
                d['mobile'] = profile.mobile
            if 'mobile_authed' in attrs:
                d['mobile_authed'] = int(profile.mobile_authed)
            if 'email_authed' in attrs:
                d['email_authed'] = int(profile.email_authed)
            if 'sex' in attrs:
                d['sex'] = profile.sex
            if 'avatar_fpath' in attrs:
                d['avatar_fpath'] = profile.avatar_fpath
            if 'origin_avatar_fpath' in attrs:
                d['origin_avatar_fpath'] = profile.origin_avatar_fpath
            if 'city_id' in attrs:
                d['city_id'] = profile.city_id if profile.city_id else 0
            if 'avatar_url' in attrs:
                d['avatar_url'] = storage.get_absolute_url(profile.avatar_fpath)
            data[profile.user_id].update(d)
            
    return data
    

def update_userinfo(user_id, **kwargs):
    u'''
    funciton: 更新用信息
    
    
    user_id: 用户id
    
    Profile表相关
    utype: 用户类型
    city_id: 城市id
    sex: 性别(settings.UserSexEnum)
    origin_avatar_fpath: 头像原文件本地路径
    avatar_fpath: 头像本地路径
    open_avatar_url: 第三方登录用户头像url
    mobile: 手机号码
    email_authed: 邮箱绑定状态
    mobile_authed: 手机绑定状态
    
    User表相关
    nick_name: 用户昵称
    email: email
    '''
    
    profiles = Profile.objects.only('utype', 'city', 'sex', 'origin_avatar_fpath', 'avatar_fpath', 'email_authed', 'mobile_authed').filter(user_id=user_id)[0:1]
    if not profiles:
        return 
    
    profile = profiles[0]
    profile_changed = False
    
    # 更新所在城市
    if kwargs.has_key('utype') and (profile.utype != kwargs['utype']):
        profile.utype = kwargs['utype']
        profile_changed = True
    
    # 更新所在城市
    if kwargs.has_key('city_id') and (profile.city_id != kwargs['city_id']):
        profile.city_id = kwargs['city_id']
        profile_changed = True
    
    # 更新性别
    if kwargs.has_key('sex') and kwargs['sex'] and (profile.sex != kwargs['sex']):
        profile.sex = kwargs['sex']
        profile_changed = True
    
    # 更新头像原文件路径
    if kwargs.has_key('origin_avatar_fpath') and kwargs['origin_avatar_fpath'] and (profile.origin_avatar_fpath != kwargs['origin_avatar_fpath']):
        profile.origin_avatar_fpath = kwargs['origin_avatar_fpath']
        profile_changed = True
    
    # 更新头像文件路径
    if kwargs.has_key('avatar_fpath') and kwargs['avatar_fpath'] and (profile.avatar_fpath != kwargs['avatar_fpath']):
        profile.avatar_fpath = kwargs['avatar_fpath']
        profile_changed = True
    
    # 更新第三方头像为用户头像（仅当用户未设置自己头像时有效)
    if kwargs.has_key('open_avatar_url') and (profile.avatar_fpath == settings.DEFAULT_AVATAR_FPATH):
        fpath = storage.save_url(kwargs['open_avatar_url'], settings.ACCOUNT_MEDIA_PATH)
        if fpath:
            profile.origin_avatar_fpath = fpath
            profile.avatar_fpath = fpath
            profile_changed = True
    
    # 更新手机号码
    if kwargs.has_key('mobile') and (profile.mobile != bool(kwargs['mobile'])):
        profile.mobile = kwargs['mobile']
        profile_changed = True
    
    # 更新手机认证状态
    if kwargs.has_key('mobile_authed') and (profile.mobile_authed != bool(kwargs['mobile_authed'])):
        profile.mobile_authed = kwargs['mobile_authed']
        profile_changed = True
    
    # 更新邮箱认证状态
    if kwargs.has_key('email_authed') and (profile.email_authed != bool(kwargs['email_authed'])):
        profile.email_authed = kwargs['email_authed']
        profile_changed = True
    
    if profile_changed:
        profile.save()
    
    user_update_fields = {}
    # 更新用户昵称
    if kwargs.has_key('nick_name') and kwargs['nick_name'].strip():
        user_update_fields['first_name'] = kwargs['nick_name'].strip()
    # 更新用户email
    if kwargs.has_key('email') and kwargs['email'].strip():
        user_update_fields['email'] = kwargs['email'].strip()
    if user_update_fields:
        User.objects.filter(id=user_id).update(**user_update_fields)
        
    #发出用户信息更新信号
    if profile_changed or user_update_fields:
        userinfo_update_signal.send(Profile, user_id=user_id, fields=kwargs.keys())


def build_userinfo_cookie(user_id):
    u'''
    function: 生成用户信息cookie value
    
    user_id - 用户id
    
    return: userinfo cookie value
    '''
    
    userinfo = fetch_userinfo(user_id, attrs=['nick_name'])
    
    val = {
        'user_id': user_id,
        'user_name': userinfo['nick_name'].encode('utf-8'),
        'true_name': userinfo['nick_name'].encode('utf-8'),
        'avatar': storage.get_absolute_url(settings.DEFAULT_AVATAR_FPATH).encode('utf-8'),
        'role': 'consumer',
        'message_count': 0,
        }
    
    return urllib.quote(urllib.urlencode(val))
    #response.set_cookie('userinfo', urllib.quote(urllib.urlencode(userinfo)), max_age=settings.SESSION_COOKIE_AGE, domain=settings.SESSION_COOKIE_DOMAIN)
